<template>
  <div class="thickness-judge-container">
    <!-- 搜索区域 -->
    <div class="search-panel">
      <!-- Search Row 1 -->
      <div class="search-row">
        <div class="search-item">
          <span class="label">时间</span>
          <el-date-picker
            v-model="searchParams.dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            class="custom-date-picker"
            size="small"
          />
        </div>
        <div class="search-item range-item">
          <span class="label">产品厚度</span>
          <el-input
            v-model="searchParams.prodThicknessMin"
            placeholder="最小值"
            class="range-input"
            size="small"
          />
          <span class="separator">-</span>
          <el-input
            v-model="searchParams.prodThicknessMax"
            placeholder="最大值"
            class="range-input"
            size="small"
          />
        </div>
        <div class="search-item range-item">
          <span class="label">原料宽度</span>
          <el-input
            v-model="searchParams.materialWidthMin"
            placeholder="最小值"
            class="range-input"
            size="small"
          />
          <span class="separator">-</span>
          <el-input
            v-model="searchParams.materialWidthMax"
            placeholder="最大值"
            class="range-input"
            size="small"
          />
        </div>
        <div class="search-item range-item">
          <span class="label">原料厚度</span>
          <el-input
            v-model="searchParams.materialThicknessMin"
            placeholder="最小值"
            class="range-input"
            size="small"
          />
          <span class="separator">-</span>
          <el-input
            v-model="searchParams.materialThicknessMax"
            placeholder="最大值"
            class="range-input"
            size="small"
          />
        </div>
        <div class="search-item">
          <span class="label">钢种</span>
          <el-select
            v-model="searchParams.steelGrade"
            placeholder="请选择"
            clearable
            class="custom-select"
            size="small"
            style="width: 120px"
          >
            <el-option label="SPHC-LT" value="SPHC-LT" />
            <el-option label="SPHC-H" value="SPHC-H" />
            <el-option label="Q235B" value="Q235B" />
          </el-select>
        </div>
      </div>
      <!-- Search Row 2 -->
      <div class="search-row">
        <div class="search-item">
          <span class="label">冷轧号</span>
          <el-input
            v-model="searchParams.coldRollNo"
            placeholder="请输入"
            class="custom-input"
            size="small"
          />
        </div>
        <div class="search-item">
          <span class="label">热轧号</span>
          <el-input
            v-model="searchParams.hotRollNo"
            placeholder="请输入"
            class="custom-input"
            size="small"
          />
        </div>
        <div class="search-item">
          <span class="label">异常筛选</span>
          <el-select
            v-model="searchParams.thkFlag"
            placeholder="请选择"
            clearable
            class="custom-select"
            size="small"
          >
            <el-option label="是" value="NO" />
            <el-option label="否" value="OK" />
          </el-select>
        </div>
        <div class="search-actions">
          <button class="btn query-btn" @click="handleSearch">查询</button>
          <button class="btn reset-btn" @click="handleReset">重置</button>
          <button class="btn export-btn">导出</button>
        </div>
      </div>
    </div>

    <!-- 主内容区域 (可上下拖动调整) -->
    <div class="main-content">
      <!-- 顶部面板：表格 + 分页 -->
      <div class="top-panel" ref="topPanelRef">
        <div class="table-container">
          <el-table
            :data="tableData"
            style="width: 100%"
            height="100%"
            border
            highlight-current-row
            @row-click="selectRow"
            :row-class-name="tableRowClassName"
            :cell-class-name="tableCellClassName"
            :header-cell-style="tableHeaderStyle"
            :cell-style="tableCellStyle"
          >
            <el-table-column type="index" label="序号" width="60" align="center" fixed="left" />
            <el-table-column prop="coldCoilID" label="冷轧号" width="140" align="center" />
            <el-table-column prop="hotCoilID" label="热轧号" width="140" align="center" />
            <el-table-column prop="steelGrade" label="钢种" width="110" align="center" />
            <el-table-column prop="exThk" label="产品厚度[mm]" width="120" align="center" />
            <el-table-column prop="exWidth" label="产品宽度[mm]" width="120" align="center" />
            <el-table-column label="超差绝对长度[m]" align="center">
              <el-table-column prop="devHead" label="头部" width="70" align="center">
                <template #default="scope">
                  <span :class="getOverallResultClass(1, scope.row)">{{ scope.row.devHead }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="devMid" label="中部" width="70" align="center">
                <template #default="scope">
                  <span :class="getOverallResultClass(3, scope.row)">{{ scope.row.devMid }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="devTail" label="尾部" width="70" align="center">
                <template #default="scope">
                  <span :class="getOverallResultClass(2, scope.row)">{{ scope.row.devTail }}</span>
                </template>
              </el-table-column>
            </el-table-column>
            <el-table-column prop="materialThickness" label="原料厚度[mm]" width="120" align="center" />
            <el-table-column prop="materialWidth" label="原料宽度[mm]" width="120" align="center" />
            <el-table-column label="命中率[%]" align="center">
              <el-table-column prop="rateHead" label="头部" width="70" align="center" />
              <el-table-column prop="rateMid" label="中部" width="70" align="center" />
              <el-table-column prop="rateTail" label="尾部" width="70" align="center" />
            </el-table-column>
            <el-table-column prop="prodEndTime" label="生产完成时间" width="160" align="center">
              <template #default="scope">
                {{ formatDateTime(scope.row.prodEndTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="headThkOvrdiffCause" label="头部超差原因" width="280" align="center" />
            <el-table-column prop="midThkOvrdiffCause" label="中部超差原因" width="280" align="center" />
            <el-table-column label="详情" width="240" fixed="right" align="center">
              <template #default="scope">
                <button class="action-btn rate-btn" @click="openDialog(scope.row)">详情</button>
                <button class="action-btn abnormal-btn" @click="openAbnormalDialog(scope.row)">异常明细</button>
                <button class="action-btn analysis-btn">厚度质量分析</button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 30, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
            background
            size="small"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>

      <!-- 分隔条 -->
      <div class="splitter" @mousedown="startDrag"></div>

      <div class="middle-panel" v-if="selectedRow">
        <div class="middle-detail-grid">
          <div class="detail-card stats-card">
            <div class="detail-header">统计结果</div>
            <div class="detail-content stats-table-wrapper">
              <el-table
                :data="formattedStatsData"
                style="width: 100%"
                height="100%"
                border
                size="small"
                :header-cell-style="statsTableHeaderStyle"
                :cell-style="statsTableCellStyle"
              >
                <el-table-column
                  prop="type"
                  label
                  width="70"
                  align="center"
                  :cell-style="{ fontWeight: 'bold' }"
                />
                <el-table-column
                  prop="headMaxDev"
                  label="头部超差最大值[mm]"
                  min-width="150"
                  align="center"
                />
                <el-table-column
                  prop="headMinDev"
                  label="头部超差最小值[mm]"
                  min-width="150"
                  align="center"
                />
                <el-table-column
                  prop="tailMaxDev"
                  label="尾部超差最大值[mm]"
                  min-width="150"
                  align="center"
                />
                <el-table-column
                  prop="tailMinDev"
                  label="尾部超差最小值[mm]"
                  min-width="150"
                  align="center"
                />
                <el-table-column
                  prop="headTotalLength"
                  label="头尾超差总长度[m]"
                  min-width="150"
                  align="center"
                />
                <el-table-column
                  prop="headAvgLength"
                  label="头尾超差平均长度[m]"
                  min-width="150"
                  align="center"
                />
                <el-table-column
                  prop="tailTotalLength"
                  label="尾部超差总长度[m]"
                  min-width="150"
                  align="center"
                />
                <el-table-column
                  prop="tailAvgLength"
                  label="尾部超差平均长度[m]"
                  min-width="150"
                  align="center"
                />
              </el-table>
            </div>
          </div>
        </div>
      </div>

      <!-- 底部面板：详情区域 -->
      <div class="bottom-panel" v-if="selectedRow">
        <div class="detail-grid">
          <!-- 厚度头尾超差趋势 -->
          <div class="detail-card chart-card">
            <div class="detail-header">厚度头尾超差趋势</div>
            <div class="detail-content chart-wrapper">
              <div class="legend">
                <span class="legend-item">
                  <span class="color-box head-max"></span>头部超差最大值
                </span>
                <span class="legend-item">
                  <span class="color-box tail-max"></span>尾部超差最大值
                </span>
              </div>
              <div class="chart-instance" ref="trendChartRef"></div>
            </div>
          </div>

          <!-- 单卷厚度等级分布图 -->
          <div class="detail-card chart-card">
            <div class="detail-header">单卷厚度等级分布图</div>
            <div class="detail-content chart-wrapper">
              <div class="chart-description">厚度等级</div>
              <div class="chart-instance" ref="distributionChartRef"></div>
            </div>
          </div>
        </div>
      </div>
      <!-- 底部面板占位符 (当未选择行时) -->
      <div class="bottom-panel-placeholder" v-else></div>
    </div>

    <!--    弹窗-->
    <el-dialog
      v-model="diglogShow"
      class="layout-dialog"
      width="80%"
      top="2vh"
      append-to-body
      style="background:#263451"
      @close="close"
    >
      <div id="data-view">
        <div class="layout-search">
          <div class="layout-search">
            <dv-border-box-11 :title="dialogTitle1">
              <div style="overflow: hidden;">
                <el-row>
                  <el-col :span="24">
                    <dv-border-box-10 style="margin: 5px;">
                      <div class="test-1">
                        <div class="wzta">
                          厚度头部超差位置(m):
                          <a class="weizhi">{{ thk_head_tole_pos }}</a>
                        </div>
                        <div class="wzta">
                          厚度本体超差位置(m):
                          <a class="weizhi">{{ thk_mid_tole_pos }}</a>
                        </div>
                        <div class="wzta">
                          厚度尾部超差位置(m):
                          <a class="weizhi">{{ thk_tail_tole_pos }}</a>
                        </div>
                        <div class="wzta">
                          厚度全长超差位置(m):
                          <a class="weizhi">{{ thk_pos }}</a>
                        </div>
                      </div>
                    </dv-border-box-10>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <dv-border-box-10>
                      <div id="app2" style="width:98%;height:300px" />
                    </dv-border-box-10>
                  </el-col>
                  <el-col :span="12">
                    <dv-border-box-10>
                      <div id="app4" style="width:98%;height:300px" />
                    </dv-border-box-10>
                  </el-col>
                </el-row>
                
              </div>
            </dv-border-box-11>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 异常明细弹窗 -->
    <el-dialog
      v-model="abnormalDialogVisible"
      :title="abnormalDialogTitle"
      width="85%"
      top="3vh"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      class="abnormal-dialog"
      :show-close="true"
    >
      <div class="abnormal-dialog-content">

        <!-- 表格区域 -->
        <div class="abnormal-table-panel">
          <el-table
            :data="abnormalTableData"
            style="width: 100%"
            height="300"
            border
            highlight-current-row
            :cell-class-name="abnormalTableCellClassName"
            :header-cell-style="abnormalHeaderStyle"
            :cell-style="abnormalCellStyle"
            :row-style="abnormalRowStyle"
            ref="abnormalTableRef"
            stripe
            :row-class-name="abnormalRowClassName"
          >
            <el-table-column prop="prodLine" label="产线" width="100" align="center" />
            <el-table-column prop="outMatNo" label="出口卷号" width="150" align="center" />
            <el-table-column prop="steelGrade" label="钢种" width="120" align="center" />
            <el-table-column prop="width" label="出口宽度[mm]" width="120" align="center" />
            <el-table-column prop="thickness" label="出口厚度[m]" width="120" align="center" />
            <el-table-column prop="weight" label="出口重量[kg]" width="120" align="center" />
            <el-table-column prop="defectCode" label="主缺陷代码" width="120" align="center">
              <template #default="scope">
                <span :class="getDefectCodeClass(scope.row.defectCode)">{{ scope.row.defectCode }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="defectComment" label="主缺陷描述" min-width="200" align="left" />
            <el-table-column prop="defectClass" label="缺陷代码(头部)" width="140" align="center">
              <template #default="scope">
                <span :class="getDefectClassClass(scope.row.defectClass)">{{ scope.row.defectClass }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 头部/中部超差原因 -->
        <div class="abnormal-cause-panel">
          <div class="cause-item">
            <span class="cause-label">头部超差原因：</span>
            <span class="cause-text">{{ currentRow?.headThkOvrdiffCause || '-' }}</span>
          </div>
          <div class="cause-item">
            <span class="cause-label">中部超差原因：</span>
            <span class="cause-text">{{ currentRow?.midThkOvrdiffCause || '-' }}</span>
          </div>
        </div>

        <!-- 前四项超差因子 -->
        <div class="abnormal-cause-panel">
          <div class="cause-section-title">前四项超差因子</div>
          <div class="factor-grid">
            <div class="factor-item" v-for="(factor, index) in topFourFactors" :key="index">
              <span class="factor-label">{{ factor.name }}：</span>
              <span class="factor-value">{{ factor.value }}</span>
            </div>
          </div>
        </div>

        <!-- 分页区域 -->
        <!-- <div class="abnormal-pagination-panel">
          <el-pagination
            v-model:current-page="abnormalPagination.currentPage"
            v-model:page-size="abnormalPagination.pageSize"
            :page-sizes="[10, 20, 30, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="abnormalPagination.total"
            @size-change="handleAbnormalSizeChange"
            @current-change="handleAbnormalCurrentChange"
            background
          />
        </div> -->
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, computed, onMounted, onUnmounted, watch, nextTick } from 'vue';
  import type { TableColumnCtx } from 'element-plus';
  // --- ECharts Imports ---
  import * as echarts from 'echarts/core';
  import { LineChart, BarChart } from 'echarts/charts';
  import {
    TooltipComponent,
    GridComponent,
    LegendComponent, // Keep legend component if charts use it internally (like trend chart)
  } from 'echarts/components';
  import { CanvasRenderer } from 'echarts/renderers';
  import { thicknessAndLayOutJudgeApi } from '/@/api/thicknessAndLayOutJudge/index';
  import { historyApi } from '/@/api/furnaceTempDynamicCtrl/history';
  import {saveAs} from 'file-saver';
  import * as XLSX from 'xlsx';
  import definitionEchart from '/@/components/ModifyYAxis/definitionEchart'

  // Register ECharts components
  echarts.use([TooltipComponent, GridComponent, LegendComponent, LineChart, BarChart, CanvasRenderer]);

  // --- Refs for DOM elements ---
  const topPanelRef = ref<HTMLDivElement | null>(null);
  const trendChartRef = ref<HTMLElement | null>(null);
  const distributionChartRef = ref<HTMLElement | null>(null);

  // --- ECharts Instances ---
  let trendChartInstance: echarts.ECharts | null = null;
  let distributionChartInstance: echarts.ECharts | null = null;

  // --- State for dragging ---
  const isDragging = ref(false);
  const startY = ref(0);
  const initialTopHeight = ref(0);

  const headTotalLength = ref(0);
  const headAvgLength = ref(0);
  const tailTotalLength = ref(0);
  const tailAvgLength = ref(0);
  const abnormalDialogVisible = ref(false);
  const abnormalDialogTitle=ref('');
  const abnormalDialogTab=ref<'thickness' | 'shape'>('thickness');
  const currentRow=ref();
  const diglogShow=ref(false); //弹窗
  const dialogTitle1=ref('');
  const forData=ref('');
  const formArr=ref([]);
  const thk_tail_tole_pos=ref();
  const thk_mid_tole_pos=ref();
  const thk_head_tole_pos=ref();
  const thk_pos=ref();
  const thk_upper=ref();
  const thk_lower=ref();
  const newDialogFormVisible1_1=ref(false);
  const chartInstance=ref(null);
  const sum='';
  const echarts_data=definitionEchart.data.echarts_data.sameOp;
  const abnormalTableData = ref<any[]>([]);

  // 异常明细弹窗相关数据
  const abnormalSearchParams = reactive({
    exportRollNo: '',
    mainDefectDesc: '',
    thickness: ''
  });

  const abnormalPagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0
  });

  const yAxis=[
        {
          scale: true, //纵坐标自适应
          // boundaryGap: [0, '50%'],
          splitLine: {
            type: 'dotted',
            show: true,
            lineStyle: {
              color: '#65687d'
            }
          },
          type: 'value',
          // position: 'left',
          axisLine: {
            lineStyle: {
              color: '#ffffff'
              // width: 1 //这里是为了突出显示加上的
            }
          },
          axisLabel: {
            formatter: '{value}',
            textStyle: {
              color: '#bfbfbf' //更改坐标轴文字颜色
            }
          },
          nameTextStyle: {
            padding: [0, 0, 0, 40],
            fontSize: 16,
            color: '#bfbfbf'
          }
        },
        {
          scale: true, //纵坐标自适应
          // boundaryGap: [0, '50%'],
          splitLine: {
            type: 'dotted',
            show: true,
            lineStyle: {
              color: '#65687d'
            }
          },
          type: 'value',
          // position: 'left',
          axisLine: {
            lineStyle: {
              color: '#ffffff'
              // width: 1 //这里是为了突出显示加上的
            }
          },
          axisLabel: {
            formatter: '{value}',
            textStyle: {
              color: '#bfbfbf' //更改坐标轴文字颜色
            }
          },
          nameTextStyle: {
            padding: [0, 0, 0, 40],
            fontSize: 16,
            color: '#bfbfbf'
          }
        }
      ];

      

    const echart={
        max1: null,
        min1: null,
        max2: null,
        min2: null,
        max3: null,
        min3: null,
        max4: null,
        min4: null
      };

    const  xAxis= {
        axisLine: {
          lineStyle: {
            color: '#ffffff'
            // width: 1 //这里是为了突出显示加上的
          }
        },
        type: 'category',
        axisLabel: {
          showMaxLabel: true,
          show: true,
          textStyle: {
            color: '#bfbfbf' //更改坐标轴文字颜色
          }
        },
        nameTextStyle: {
          color: '#FFF',
          fontWeight: 'bold',
          fontSize: 16
        },
        axisTick: {
          alignWithLabel: true
        },
        name: '(m)',
        data: []
      };


  // --- Search Params ---
  const searchParams = reactive({
    dateRange: [],
    prodThicknessMin: '',
    prodThicknessMax: '',
    materialWidthMin: '',
    materialWidthMax: '',
    materialThicknessMin: '',
    materialThicknessMax: '',
    steelGrade: '',
    coldRollNo: '',
    hotRollNo: '',
    thkFlag: '',
  });

  interface FindDataParams {
    prodThicknessMin: string;
    prodThicknessMax: string;
    materialWidthMin: string;
    materialWidthMax: string;
    materialThicknessMin: string;
    materialThicknessMax: string;
    steelGrade: string;
    coldRollNo: string;
    hotRollNo: string;
    thkFlag: string;
    startDate?: string;
    endDate?: string;
    pageIndex: string;
    pageSize: string;
  }

  // --- Table Data ---
  interface TableRow {
    id: number;
    coldCoilID: string;
    hotCoilID: string;
    steelGrade: string;
    prodThickness: string;
    prodWidth: string;
    devHead: number;
    devMid: number;
    devTail: number;
    rateHead: number;
    rateMid: number;
    rateTail: number;
    materialThickness: string;
    materialWidth: string;
    rollCount: number;
    newCol1: string;
    newCol2: string;
  }

  // --- Table Data ---
  interface RecordTableRow {
    coldCoilID: string;
    hotCoilID: string;
    steelGrade: string;
    exThk: string;
    exWidth: string;
    thkHeadToleAbsLen: string;
    thkMidToleAbsLen: string;
    thkTailToleAbsLen: string;
    thkHeadHitRate: number;
    thkMidHitRate: number;
    thkTailHitRate: number;
    enThk: string;
    enWidth: string;
  }
  const tableData = ref<TableRow[]>([]);

  // --- Selected Row ---
  const selectedRow = ref<TableRow | null>(null);

  // --- Pagination ---
  const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: tableData.value.length, // Should be updated based on actual data length from API
  });

  // --- Statistics Data ---
  const formattedStatsData = computed(() => {
    if (!selectedRow.value) return [];
    // Replace with actual calculations based on selectedRow or fetched detail data
    const staticValues = {
      headMaxDev: selectedRow.value.thkHeadToleMaxValue.toFixed(3),
      headMinDev: selectedRow.value.thkHeadToleMinValue.toFixed(3),
      tailMaxDev: selectedRow.value.thkTailToleMaxValue.toFixed(3),
      tailMinDev: selectedRow.value.thkTailToleMinValue.toFixed(3),
      headTotalLength: headTotalLength.value,
      headAvgLength: headAvgLength.value,
      tailTotalLength: tailTotalLength.value,
      tailAvgLength: tailAvgLength.value,
    };

    return [
      {
        type: '值',
        ...staticValues,
      },
      {
        type: '对应卷号',
        headMaxDev: selectedRow.value.coldCoilID,
        headMinDev: selectedRow.value.coldCoilID,
        tailMaxDev: selectedRow.value.coldCoilID,
        tailMinDev: selectedRow.value.coldCoilID,
        headTotalLength: '-',
        headAvgLength: '-',
        tailTotalLength: '-',
        tailAvgLength: '-',
      },
      {
        type: '热轧号',
        headMaxDev: selectedRow.value.hotCoilID,
        headMinDev: selectedRow.value.hotCoilID,
        tailMaxDev: selectedRow.value.hotCoilID,
        tailMinDev: selectedRow.value.hotCoilID,
        headTotalLength: '-',
        headAvgLength: '-',
        tailTotalLength: '-',
        tailAvgLength: '-',
      },
    ];
  });

  // --- Chart Options ---
  // Trend Chart Option
  const trendChartOption = {
    backgroundColor: 'transparent',
    tooltip: { trigger: 'axis', backgroundColor: 'rgba(10, 26, 58, 0.8)', borderColor: '#3a5a8a', textStyle: { color: '#c0c4cc' } },
    grid: { left: '10%', right: '5%', bottom: '15%', top: '12%', containLabel: true },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: Array.from({ length: 10 }, (_, i) => `${i + 1}`), // Sample length points
      axisLine: { lineStyle: { color: '#3a5a8a' } },
      axisLabel: { color: '#c0c4cc', fontSize: 10 },
    },
    yAxis: {
      type: 'value',
      axisLabel: { color: '#c0c4cc', fontSize: 10, formatter: '{value} mm' },
      splitLine: { lineStyle: { color: 'rgba(58, 90, 138, 0.3)' } },
      axisLine: { lineStyle: { color: '#3a5a8a' } },
    },
    series: [
      {
        name: '头部超差最大值',
        type: 'line',
        smooth: true,
        symbol: 'none',
        itemStyle: { color: '#67c23a' }, // Green
        lineStyle: { width: 2 },
        // Generate random data dynamically based on selected row for simulation
        data: Array.from({ length: 10 }, () => (0.45 + Math.random() * 0.1).toFixed(3)),
      },
      {
        name: '尾部超差最大值',
        type: 'line',
        smooth: true,
        symbol: 'none',
        itemStyle: { color: '#e6a23c' }, // Yellow
        lineStyle: { width: 2 },
        data: Array.from({ length: 10 }, () => (0.4 + Math.random() * 0.1).toFixed(3)),
      },
    ],
  };

  // Distribution Chart Option
  const distributionChartOption = {
    backgroundColor: 'transparent',
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      backgroundColor: 'rgba(10, 26, 58, 0.8)',
      borderColor: '#3a5a8a',
      textStyle: { color: '#c0c4cc' },
    },
    grid: { left: '10%', right: '5%', bottom: '15%', top: '12%', containLabel: true },
    xAxis: {
      type: 'category',
      data: ['A级', 'B级', 'C级', 'D级'],
      axisLine: { lineStyle: { color: '#3a5a8a' } },
      axisLabel: { color: '#c0c4cc', fontSize: 10 },
      axisTick: { alignWithLabel: true },
    },
    yAxis: {
      type: 'value',
      axisLabel: { color: '#c0c4cc', fontSize: 10, formatter: '{value} %' },
      splitLine: { lineStyle: { color: 'rgba(58, 90, 138, 0.3)' } },
      axisLine: { lineStyle: { color: '#3a5a8a' } },
    },
    series: [
      {
        name: '比例',
        type: 'bar',
        barWidth: '50%',
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#2979ff' },
            { offset: 1, color: '#1c2d5a' },
          ]),
          borderRadius: [3, 3, 0, 0],
        },
        // Generate random data dynamically
        data: [
          Math.floor(Math.random() * 70 + 20),
          Math.floor(Math.random() * 20 + 5),
          Math.floor(Math.random() * 10),
          Math.floor(Math.random() * 5),
        ],
      },
    ],
  };

  // --- Event Handlers ---
  const handleSearch = () => {
    console.log('查询参数:', searchParams);
    pagination.currentPage = 1;
    fetchTableData();
  };

  const handleReset = () => {
    Object.keys(searchParams).forEach((key) => {
      const typedKey = key as keyof typeof searchParams;
      if (typedKey === 'dateRange') searchParams[typedKey] = [];
      else searchParams[typedKey] = '';
    });
    console.log('重置参数');
    // Optionally re-fetch initial data
  };

  const selectRow = (row: TableRow) => {
    if (selectedRow.value?.id === row.coldCoilID) {
      selectedRow.value = null; // Deselect if clicking the same row
    } else {
      selectedRow.value = row;
    }
    findDataNoPage();
    console.log('选中行:', selectedRow.value);
  };

  // --- ECharts Logic ---
  const initOrUpdateCharts = () => {
    console.log('Init/Update charts called. Selected Row:', !!selectedRow.value);
    if (!selectedRow.value) return; // Should not happen if called from watch correctly

    console.log(tableData.value);

    try {
      // Trend Chart
      if (trendChartRef.value) {
        if (!trendChartInstance) {
          console.log('Initializing Trend Chart');
          trendChartInstance = echarts.init(trendChartRef.value);
          window.addEventListener('resize', resizeCharts); // Add listener only when chart exists
        }
        // Update options with potentially new (random) data
        trendChartOption.series[0].data = Array.from({ length: 10 }, (_, i) => tableData.value[i].thkHeadToleMaxValue.toFixed(3));
        trendChartOption.series[1].data = Array.from({ length: 10 }, (_, i) => tableData.value[i].thkTailToleMaxValue.toFixed(3));
        trendChartInstance.setOption(trendChartOption, true); // Use true for notMerge
      } else {
        console.warn('Trend Chart Ref not found during init/update!');
      }

      // Distribution Chart
      if (distributionChartRef.value) {
        if (!distributionChartInstance) {
          console.log('Initializing Distribution Chart');
          distributionChartInstance = echarts.init(distributionChartRef.value);
          // Resize listener already added by trend chart
        }
        distributionChartOption.series[0].data = [
          Math.floor(Math.random() * 70 + 20),
          Math.floor(Math.random() * 20 + 5),
          Math.floor(Math.random() * 10),
          Math.floor(Math.random() * 5),
        ];
        distributionChartInstance.setOption(distributionChartOption, true); // Use true for notMerge
      } else {
        console.warn('Distribution Chart Ref not found during init/update!');
      }
    } catch (error) {
      console.error('图表初始化/更新失败:', error);
    }
  };

  const disposeCharts = () => {
    console.log('Disposing charts...');
    window.removeEventListener('resize', resizeCharts); // Remove listener
    trendChartInstance?.dispose();
    distributionChartInstance?.dispose();
    trendChartInstance = null;
    distributionChartInstance = null;
  };

  const resizeCharts = () => {
    console.log('Resizing charts...');
    trendChartInstance?.resize();
    distributionChartInstance?.resize();
  };

  // --- Watcher for Selected Row ---
  watch(selectedRow, (newRow, oldRow) => {
    if (newRow) {
      console.log('Watcher: Row selected, initializing/updating charts soon...');
      nextTick(() => {
        initOrUpdateCharts();
      });
    } else {
      console.log('Watcher: Row deselected, disposing charts...');
      disposeCharts();
    }
  });

  // --- Dragging Logic ---
  const startDrag = (event: MouseEvent) => {
    if (!topPanelRef.value) return;
    isDragging.value = true;
    startY.value = event.clientY;
    initialTopHeight.value = topPanelRef.value.offsetHeight;
    document.body.style.cursor = 'row-resize';
    document.body.style.userSelect = 'none';
    window.addEventListener('mousemove', doDrag);
    window.addEventListener('mouseup', stopDrag);
  };

  const doDrag = (event: MouseEvent) => {
    if (!isDragging.value || !topPanelRef.value) return;
    const deltaY = event.clientY - startY.value;
    let newHeight = initialTopHeight.value + deltaY;

    const container = topPanelRef.value.parentElement as HTMLElement;
    const containerHeight = container ? container.offsetHeight : window.innerHeight;
    const splitterHeight = 8; // Splitter height
    const minPanelHeight = 150; // Min height for top and bottom panels

    const maxTopHeight = containerHeight - splitterHeight - minPanelHeight;

    if (newHeight < minPanelHeight) newHeight = minPanelHeight;
    if (newHeight > maxTopHeight) newHeight = maxTopHeight;

    topPanelRef.value.style.height = `${newHeight}px`;
  };

  const stopDrag = () => {
    if (!isDragging.value) return;
    isDragging.value = false;
    document.body.style.cursor = '';
    document.body.style.userSelect = '';
    window.removeEventListener('mousemove', doDrag);
    window.removeEventListener('mouseup', stopDrag);
  };

  // --- ElTable Style Definitions ---
  const tableHeaderStyle = {
    background: '#183272',
    color: '#b8e8ff',
    padding: '6px 0',
    textAlign: 'center',
    fontWeight: 'normal',
    borderBottom: '1px solid #06279d',
  };
  const tableCellStyle = {
    padding: '6px 0',
    textAlign: 'center',
    color: '#c0c4cc',
    borderBottom: '1px solid #06279d',
    borderRight: '1px solid #06279d',
    fontSize: '12px',
  };
  const statsTableHeaderStyle = {
    background: '#0f2142',
    color: '#b8e8ff',
    padding: '5px 0',
    textAlign: 'center',
    fontWeight: 'normal',
    border: '1px solid #3a5a8a',
  };
  const statsTableCellStyle = {
    background: '#0f2142',
    color: '#c0c4cc',
    padding: '5px 0',
    textAlign: 'center',
    border: '1px solid #3a5a8a',
    fontSize: '12px',
  };

function openDialog(row:any) {

  diglogShow.value = true
  dialogTitle1.value = '冷卷号:' + row.coldCoilID
  forData.value = row.hotCoilID
  formArr.value = []
  formArr.value.push(row.coldCoilID)
  console.log("row"+row)

  thk_tail_tole_pos.value = row.thkTailTolePos
  thk_mid_tole_pos.value = row.thkMidTolePos
  thk_head_tole_pos.value = row.thkHeadTolePos
  thk_pos.value = row.thkPos
  thk_upper.value = row.thkUpper
  thk_lower.value = row.thkLower
  findAll_a(row.coldCoilID)
  findAll4(row.coldCoilID)
  newDialogFormVisible1_1.value = true
}

async function findAll4(coil:any) {
  let params = [
    'tcm_s5_thk_diff',
    'tcm_exs5_thk_act',
    'tcm_s5_strip_speed_act'
  ]
  const graphParam = {
    line: 'TCM2280',
    extid: [coil],
    curve: params,
  };
  const res = await historyApi.getgraphData(graphParam);

  if (res.data.data.curve[0].tcm_s5_thk_diff) {
    // echart_thickdiff_time(
    //   res.data.data.send_time,
    //   res.data.data.curve[0].tcm_s5_thk_diff
    // )
  } else {
    echarts_no('app6')
  }

  if (
    !res.data.data.curve[0].tcm_exs5_thk_act &&
    !res.data.data.curve[0].tcm_s5_strip_speed_act
  ) {
    //echarts_no('app8')
  } else {
    // echart_speed_time(
    //   res.data.data.send_time,
    //   res.data.data.curve[0].tcm_exs5_thk_act,
    //   res.data.data.curve[0].tcm_s5_strip_speed_act
    // )
  }
};

//厚度偏差(时间)
    function echart_thickdiff_time(dataX:any, dataY:any) {
      xAxis.data = dataX
      yAxis[0].min = echart.min3
      yAxis[0].max = echart.max3
      echarts_data.legend.data = ['厚度偏差(时间)']
      yAxis[0].name = '(um)'
      yAxis[1].name = ''
      var myChart2 = echarts.init(document.getElementById('app6'))
      // 指定图表的配置项和数据
      var option2 = {
        title: {
          text: '厚度偏差(时间序列)',
          textStyle: {
            color: '#fff'
          }
        },
        tooltip: echarts_data.tooltip,
        color: echarts_data.color,
        legend: echarts_data.legend,
        grid: echarts_data.grid,
        toolbox: echarts_data.toolbox,
        dataZoom: echarts_data.dataZoom,
        xAxis: xAxis,
        yAxis: yAxis,
        series: [
          {
            type: 'line',
            stack: 'Total',
            data: dataY
          }
        ]
      }
      // 使用刚指定的配置项和数据显示图表。
      myChart2.setOption(option2)
    };


function echart_speed_time(dataX:any, dataY1:any, dataY2:any) {
      yAxis[0].min = echart.min4
      yAxis[0].max = echart.max4
      yAxis[0].name = '(mm)'
      yAxis[1].name = '(m/min)'
      xAxis.data = dataX
      var myChart = echarts.init(document.getElementById('app8'))
      // 指定图表的配置项和数据
      var option = {
        title: [
          {
            text: '',
            left: 'left',
            textStyle: {
              color: '#ccc',
              fontWeight: 'bold',
              fontSize: 18
            }
          },
          {
            left: 'center',
            top: 20,
            textStyle: {
              color: '#ccc',
              fontWeight: 'bold',
              fontSize: 14
            }
          }
        ],
        tooltip: echarts_data.tooltip,
        color: echarts_data.color,
        legend: echarts_data.legend,
        grid: echarts_data.grid,
        toolbox: echarts_data.toolbox,
        dataZoom: echarts_data.dataZoom,
        xAxis: xAxis,
        yAxis: yAxis,
        series: [
          {
            name: 'S5机架厚度(时间)',
            type: 'line',
            data: dataY1, //.reverse()
            markLine: {
              lineStyle: {
                normal: {
                  type: 'solid',
                  color: '#fff' // 这儿设置安全基线颜色
                }
              },
              data: [
                {
                  yAxis: thk_upper,
                  name: '厚度上限',
                  label: {
                    show: true,
                    position: 'insideEndTop',
                    formatter: '厚度上限:{c} '
                  }
                },
                {
                  yAxis: thk_lower,
                  name: '厚度下限',
                  label: {
                    show: true,
                    position: 'insideEndTop',
                    formatter: '厚度下限:{c} '
                  }
                }
              ],
              label: {
                normal: {
                  show: true // 这儿设置安全基线
                }
              }
            }
          },
          {
            yAxisIndex: 1,
            name: 'S5带钢速度',
            type: 'line',
            data: dataY2 //.reverse()
          }
        ]
      }
      myChart.clear()
      // 使用刚指定的配置项和数据显示图表。
      myChart.setOption(option)
    };

//长度序列曲线
async function findAll_a(coil_id:any) {

  let params = [
    'tcm_s5_thk_diff',
    'tcm_exs5_thk_act',
    'tcm_s5_strip_speed_act'
    
  ]


  const graphParam = {
    line: 'TCM2280',
    extid: [coil_id],
    curve: params,
  };
  const res = await historyApi.getgraphData(graphParam);
  //5机架厚度偏差
  if (
    res.data.data.curve[0].tcm_s5_thk_diff &&
    res.data.data.curve[0].tcm_s5_thk_diff.length != 0
  ) {
    echart_test2(res.data.data.curve[0].tcm_s5_thk_diff)
  } else {
    echarts_no('app2')
  }
  //5机架出口厚度实际/5机架出口速度
  if (!res.data.data.curve[0].tcm_exs5_thk_act && !res.data.data.curve[0].tcm_s5_strip_speed_act) {
    echarts_no('app4')
  } else {
    let dataX:any = []
    let dataY1:any = []
    let dataY2:any = []
    if (res.data.data.curve[0].tcm_s5_strip_speed_act) {
      dataX = []
      res.data.data.curve[0].tcm_s5_strip_speed_act.forEach((item, index) => {
        dataX.push(index + 1)
        dataY2.push(item.toFixed(1))
      })
    }
    if (res.data.data.curve[0].tcm_exs5_thk_act) {
      dataX = []
      res.data.data.curve[0].tcm_exs5_thk_act.forEach((item, index) => {
        dataX.push(index + 1)
        dataY1.push(item.toFixed(3))
      })
    }
    echart_speed_length(dataY1, dataY2, dataX)
  }
};

//厚度偏差(长度序列)
function echart_test2(seriesData:any) {
      // let textTitle = ''
      // if (thickFlag == 1) {
      //   textTitle = '4-1'
      // } else {
      //   textTitle = 'L1'
      // }
      var xData = []
      var yData = []
      for (var i = 0; i <= seriesData.length; i++) {
        xData.push(i + 1)
        yData.push(seriesData[i])
      }

      yAxis[0].min = echart.min1
      yAxis[0].max = echart.max1
      echarts_data.legend.data = ['厚度偏差(长度)']
      yAxis[0].name = '(um)'
      xAxis.data = xData
      var myChart1 = echarts.init(document.getElementById('app2')) //将配置注入到html中定义的容器
      var option1 = {
        title: [
          {
            text: '厚度偏差(长度)',
            left: 'left',
            textStyle: {
              fontSize: 16,
              fontWeight: 700,
              color: '#ffffff'
            }
          },
          {
            // text: this.forData,
            left: 'center',
            textStyle: {
              color: '#ccc',
              fontWeight: 'bold',
              fontSize: 14
            }
          }
        ],
        // tooltip: echarts_data.tooltip,
        color: ['#FFCD39', '#0decb1'],
        xAxis: xAxis,
        yAxis: yAxis,
        series: [
          {
            name: '',
            type: 'line',
            step: 'start',
            data: yData
            // markLine: {
            //   lineStyle: {
            //     normal: {
            //       type: 'dashed',
            //       color: '#FFFF00 ' // 这儿设置安全基线颜色
            //     }
            //   },
            //   data: [
            //     {
            //       yAxis: null,
            //       label: {
            //         show: true,
            //         position: 'end',
            //         formatter: '{c} '
            //       }
            //     },
            //     {
            //       yAxis: null,
            //       label: {
            //         show: true,
            //         position: 'end',
            //         formatter: '{c} '
            //       }
            //     }
            //   ],
            //   label: {
            //     normal: {
            //       show: true // 这儿设置安全基线
            //     }
            //   }
            // }
          }
        ]
      }

      myChart1.clear()
      myChart1.setOption(option1)
      // this.chartInstance = myChart1
    };

    // 无数据时：展示暂无数据
   function echarts_no(e:any) {
      const dom = document.getElementById(e)
      dom.innerHTML = '暂无数据'
      dom.style.cssText =
        'text-align:center; color: #999; border: none;line-height: 300px'
      dom.removeAttribute('_echarts_instance_')
    };

    //5机架速度/厚度曲线--长度序列
    function echart_speed_length(dataY1, dataY2, dataX) {
      // const arrlength = Array.from({ length: data.length }, (_, i) => i + 1)
      yAxis[0].name = '(mm)'
      yAxis[1].name = '(m/min)'
      yAxis[0].min = echart.min2
      yAxis[0].max = echart.max2
      xAxis.data = dataX
      echarts_data.legend.data = ['S5机架厚度', 'S5带钢速度']
      var myChart2 = echarts.init(document.getElementById('app4'))

      myChart2.clear()
      // 指定图表的配置项和数据
      myChart2.setOption({
        title: {
          text: '',
          x: 'left',
          top: '0%',
          left: '0%',
          textStyle: {
            fontSize: 16,
            fontWeight: 700,
            color: '#ffffff'
          }
        },
        tooltip: echarts_data.tooltip,
        color: echarts_data.color,
        legend: echarts_data.legend,
        dataZoom: echarts_data.dataZoom,
        toolbox: echarts_data.toolbox,
        grid: echarts_data.grid,
        xAxis: xAxis,
        yAxis: yAxis,
        series: [
          {
            type: 'line',
            smooth: true,
            data: dataY1,
            yAxisIndex: 0,
            name: 'S5机架厚度',
            showSymbol: false,
            markLine: {
              lineStyle: {
                normal: {
                  type: 'solid',
                  color: '#fff' // 这儿设置安全基线颜色
                }
              },
              data: [
                {
                  yAxis: thk_upper,
                  name: '厚度上限',
                  label: {
                    show: true,
                    position: 'insideEndTop',
                    formatter: '厚度上限:{c} '
                  }
                },
                {
                  yAxis: thk_lower,
                  name: '厚度下限',
                  label: {
                    show: true,
                    position: 'insideEndTop',
                    formatter: '厚度下限:{c} '
                  }
                }
              ],
              label: {
                normal: {
                  show: true // 这儿设置安全基线
                }
              }
            }
          },
          {
            type: 'line',
            smooth: true,
            data: dataY2,
            yAxisIndex: 1,
            name: 'S5带钢速度',
            showSymbol: false
          }
        ]
      })
      chartInstance.value = myChart2
    };

  // --- ElTable Class Helpers ---
  const tableRowClassName = ({ row }: { row: TableRow }) => (selectedRow.value?.id === row.id ? 'selected-row' : '');
  const tableCellClassName = ({ row, column }: CellClassNameParams) => {
    if (column.property === 'devHead' && row.devHead > 10) return 'red-text';
    if (column.property === 'devMid' && row.devMid > 5) return 'red-text';
    if (column.property === 'devTail' && row.devTail > 5) return 'red-text';
    return '';
  };
  interface CellClassNameParams {
    row: TableRow;
    column: TableColumnCtx<TableRow>;
    rowIndex: number;
    columnIndex: number;
  }
    // 时间格式化函数
  const formatDateTime = (dateTime: string | null | undefined): string => {
    if (!dateTime) return '-';
    
    try {
      // 如果是数字格式的时间戳，先转换为字符串
      const dateStr = String(dateTime);
      
      // 处理不同格式的时间字符串
      let date: Date;
      
      // 如果是纯数字格式 (YYYYMMDDHHmmss)
      if (/^\d{14}$/.test(dateStr)) {
        const year = parseInt(dateStr.substring(0, 4));
        const month = parseInt(dateStr.substring(4, 6)) - 1;
        const day = parseInt(dateStr.substring(6, 8));
        const hour = parseInt(dateStr.substring(8, 10));
        const minute = parseInt(dateStr.substring(10, 12));
        const second = parseInt(dateStr.substring(12, 14));
        date = new Date(year, month, day, hour, minute, second);
      }
      // 如果是标准日期时间格式
      else if (dateStr.includes('-') || dateStr.includes('/')) {
        date = new Date(dateStr);
      }
      // 其他格式尝试直接解析
      else {
        date = new Date(dateStr);
      }
      
      // 检查日期是否有效
      if (isNaN(date.getTime())) {
        return '-';
      }
      
      // 格式化为 YYYY-MM-DD HH:mm:ss
      const pad = (num: number) => num.toString().padStart(2, '0');
      return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
    } catch (error) {
      console.error('时间格式化错误:', error);
      return '-';
    }
  };

  // --- Lifecycle Hooks ---
  onMounted(() => {
    // Add resize listener for charts (only if/when they are initialized)

    fetchTableData();
    findDataNoPage();
  });

  const fetchTableData = async () => {
    try {
      const formatDate = (date: string | Date | null | undefined): string | undefined => {
        if (!date) return undefined;
        if (date instanceof Date) {
          const pad = (num: number) => num.toString().padStart(2, '0');
          return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(
            date.getSeconds()
          )}`;
        }
        return date;
      };

      if (searchParams.dateRange == null) {
        searchParams.dateRange = [];
      }

      const params: FindDataParams = {
        prodThicknessMin: searchParams.prodThicknessMin,
        prodThicknessMax: searchParams.prodThicknessMax,
        materialWidthMin: searchParams.materialWidthMax,
        materialWidthMax: searchParams.materialWidthMax,
        materialThicknessMin: searchParams.materialThicknessMin,
        materialThicknessMax: searchParams.materialThicknessMax,
        steelGrade: searchParams.steelGrade,
        coldRollNo: searchParams.coldRollNo,
        hotRollNo: searchParams.hotRollNo,
        thkFlag: searchParams.thkFlag,
        startDate: formatDate(searchParams.dateRange[0]),
        endDate: formatDate(searchParams.dateRange[1]),
        pageIndex: String(pagination.currentPage),
        pageSize: String(pagination.pageSize),
      };

      Object.keys(params).forEach((key) => {
        if (params[key as keyof FindDataParams] === undefined) {
          delete params[key as keyof FindDataParams];
        }
      });

      const response = await thicknessAndLayOutJudgeApi.findByPage(params);

      if (response && response.data && Array.isArray(response.data.data.records)) {
        const responsePayload = response.data.data;
        const records = responsePayload.records;

        const mappedData = records.map((record: RecordTableRow) => {
          return {
            devHead: record.thkHeadToleAbsLen,
            devMid: record.thkMidToleAbsLen,
            devTail: record.thkTailToleAbsLen,
            rateHead: record.thkHeadHitRate * 100,
            rateMid: record.thkMidHitRate * 100,
            rateTail: record.thkTailHitRate * 100,
            materialThickness: record.enThk,
            materialWidth: record.enWidth,
            ...record,
          };
        });

        tableData.value = mappedData;
        // (headTotalLength.value = response.data.bean.sum1),
        //   (headAvgLength.value = response.data.bean.ave1),
        //   (tailTotalLength.value = response.data.bean.sum2),
        //   (tailAvgLength.value = response.data.bean.ave2),
          (pagination.total = responsePayload.total);
        ElMessage.success(responsePayload.msg || '查询成功');
      } else {
        ElMessage.info(response?.data?.msg || '未查询到数据或响应格式不正确');
        tableData.value = [];
        pagination.total = 0;
      }
    } catch (error: any) {
      console.error('获取数据失败:', error);
      ElMessage.error(error.response?.data?.msg || error.message || '获取数据失败');
      tableData.value = [];
      pagination.total = 0;
    }
  };

  function openAbnormalDialog(row:any) {
    abnormalDialogVisible.value = true;
    abnormalDialogTitle.value = '异常明细 - 冷轧卷号:' + row.coldCoilID;
    abnormalDialogTab.value = 'thickness';
    currentRow.value = row;
    
    // 初始化搜索参数
    abnormalSearchParams.exportRollNo = row.coldCoilID || '';
    abnormalSearchParams.mainDefectDesc = '';
    abnormalSearchParams.thickness = '';
    
    // 重置分页
    abnormalPagination.currentPage = 1;
    abnormalPagination.pageSize = 10;
    
    // 获取异常明细数据
    fetchAbnormalTableData();
  }
  // 获取异常明细表格数据
  const fetchAbnormalTableData = async () => {
    try {
      const param = {
        pageIndex: abnormalPagination.currentPage,
        pageSize: abnormalPagination.pageSize,
        outMatNo: abnormalSearchParams.exportRollNo,
        thickness: abnormalSearchParams.thickness,
        defectComment: abnormalSearchParams.mainDefectDesc,
      };
      
      const res = await thicknessAndLayOutJudgeApi.findThkJudge(param);
      if (res && res.data) {
        const responsePayload = res.data.data;
        const mappedData = responsePayload.map((record: any) => ({
          outMatNo: record.outMatNo,
          prodLine: record.pltcmNo,
          steelGrade: record.steelGrade,
          thickness: record.thickness,
          width: record.width,
          weight: record.weight,
          defectCode: record.defectCode,
          defectComment: record.defectComment,
          defectClass: record.defectClass,
          ...record
        }));
        
        abnormalTableData.value = mappedData;
        abnormalPagination.total = res.data.count;
      } else {
        abnormalTableData.value = [];
        abnormalPagination.total = 0;
      }
    } catch (error) {
      console.error('获取异常明细数据失败:', error);
      abnormalTableData.value = [];
      abnormalPagination.total = 0;
    }
  };

  const findDataNoPage = async () => {
    try {
      


      const response = await thicknessAndLayOutJudgeApi.findDataNoPage({});

      if (response && response.data) {
        console.log("response"+response)
        const responsePayload = response.data.data;


        
        (headTotalLength.value = responsePayload.sum1),
          (headAvgLength.value = responsePayload.ave1),
          (tailTotalLength.value = responsePayload.sum2),
          (tailAvgLength.value = responsePayload.ave2),
        ElMessage.success(responsePayload.msg || '查询成功');
      } else {
        ElMessage.info(response?.data?.msg || '未查询到数据或响应格式不正确');
        tableData.value = [];
        pagination.total = 0;
      }
    } catch (error: any) {
      console.error('获取数据失败:', error);
      ElMessage.error(error.response?.data?.msg || error.message || '获取数据失败');
      tableData.value = [];
      pagination.total = 0;
    }

  }

  const getOverallResultClass = (type: any, result: any) => {
    if (type == 1) {
      if (result.devHead > 5) {
        return 'result-no';
      }
    }
    if (type == 2) {
      if (result.devTail > 3) {
        return 'result-no';
      }
    }
    if (type == 3) {
      if (result.devMid > 0) {
        return 'result-no';
      }
    }
  };

  onUnmounted(() => {
    disposeCharts(); // Ensure cleanup on unmount
    // Clean up drag listeners
    window.removeEventListener('mousemove', doDrag);
    window.removeEventListener('mouseup', stopDrag);
  });

  const handleSizeChange = (val: number) => {
    pagination.pageSize = val;
    fetchTableData();
  };

  const handleCurrentChange = (val: number) => {
    pagination.currentPage = val;
    fetchTableData();
  };

  // 异常明细表格样式相关
  const abnormalIndexMethod = (index: number) => {
    return (abnormalPagination.currentPage - 1) * abnormalPagination.pageSize + index + 1;
  };

  const abnormalHeaderStyle = {
    background: '#2a5caa',
    color: '#fff',
    padding: '12px 10px',
    textAlign: 'center',
    fontWeight: 'bold',
    border: 'none',
    fontSize: '14px'
  };

  const abnormalCellStyle = {
    padding: '10px 10px',
    textAlign: 'center',
    color: '#c0c4cc',
    border: 'none',
    fontSize: '13px'
  };

  const abnormalRowStyle = {
    background: '#0f2142'
  };

  const abnormalRowClassName = ({ rowIndex }: { rowIndex: number }) => {
    return rowIndex % 2 === 1 ? 'abnormal-stripe-row' : '';
  };

  const abnormalTableCellClassName = ({ row, column }: { row: any; column: any }) => {
    if (column.property === 'defectCode' && typeof row.defectCode === 'number' && row.defectCode >= 10) {
      return 'abnormal-red-text';
    }
    if (column.property === 'defectClass' && typeof row.defectClass === 'number' && row.defectClass >= 10) {
      return 'abnormal-red-text';
    }
    return '';
  };

  const getDefectCodeClass = (defectCode: any) => {
    if (typeof defectCode === 'number' && defectCode >= 10) {
      return 'defect-code-high';
    }
    return 'defect-code-normal';
  };

  const getDefectClassClass = (defectClass: any) => {
    if (typeof defectClass === 'number' && defectClass >= 10) {
      return 'defect-class-high';
    }
    return 'defect-class-normal';
  };

  // 计算前四项超差因子
  const topFourFactors = computed(() => {
    if (!currentRow.value) return [];
    
    const factorFields = [
      { key: 'miSlipMidDev1', name: '厚度偏差与1轧机前滑偏差' },
      { key: 'miVectssetMidDev23', name: '厚度偏差与23机架间的张力偏差' },
      { key: 'miVecforcesetMidDev2', name: '厚度偏差与2轧机轧制力偏差' },
      { key: 'miVectssetMidDev34', name: '厚度偏差与34机架间的张力偏差' },
      { key: 'miVecforcesetMidDev3', name: '厚度偏差与3轧机轧制力偏差' },
      { key: 'miVectssetMidDev45', name: '厚度偏差与45机架间的张力偏差' },
      { key: 'miVecforcesetMidDev4', name: '厚度偏差与4轧机轧制力偏差' },
      { key: 'miVecslipactMid4', name: '厚度偏差与4轧机前滑偏差' },
      { key: 'miTcmS5StripSpeedActMid', name: '厚度偏差与5机架出口速度' }
    ];
    
    // 过滤出有值的字段并排序
    const validFactors = factorFields
      .map(field => ({
        name: field.name,
        value: currentRow.value[field.key] || 0
      }))
      .filter(factor => factor.value !== 0 && factor.value !== null && factor.value !== undefined)
      .sort((a, b) => b.value - a.value)
      .slice(0, 4); // 取前四项
    
    return validFactors;
  });
</script>

<style scoped lang="less">
/* --- Container & Base --- */
.thickness-judge-container {
  background-color: #0a1a3a;
  color: #c0c4cc;
  padding: 15px;
  height: 100vh;
  box-sizing: border-box;
  font-family: "Microsoft YaHei", "Segoe UI", sans-serif;
  font-size: 13px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* --- Search Panel --- */
.search-panel {
  background-color: #1c2d5a;
  padding: 10px 15px;
  border-radius: 3px;
  flex-shrink: 0;
  margin-bottom: 10px;
}
.search-row {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  margin-bottom: 8px;
}
.search-row:last-child {
  margin-bottom: 0;
}
.search-item {
  display: flex;
  align-items: center;
  margin-right: 15px;
  margin-bottom: 5px;
}
.label {
  color: #c0c4cc;
  margin-right: 6px;
  white-space: nowrap;
  min-width: 55px;
  text-align: right;
  font-size: 12px;
}
.range-item .label {
  min-width: 60px;
}
.range-input {
  width: 75px;
}
.separator {
  margin: 0 4px;
  color: #c0c4cc;
}
.custom-input {
  width: 130px;
}
.custom-select {
  width: 110px;
}
.search-actions {
  margin-left: auto;
  display: flex;
  align-items: center;
}

/* Buttons */
.btn {
  height: 16px;
  padding: 0 12px;
  border: none;
  border-radius: 3px;
  font-size: 12px;
  cursor: pointer;
  margin-left: 8px;
  color: #fff;
  transition: background-color 0.2s ease;
}
.query-btn {
  background-color: #2979ff;
}
.query-btn:hover {
  background-color: #5393ff;
}
.reset-btn {
  background-color: #5a7aa4;
}
.reset-btn:hover {
  background-color: #7a9ac4;
}
.export-btn {
  background-color: #67c23a;
}
.export-btn:hover {
  background-color: #85ce61;
}

/* Element Plus Overrides (Size Small) */
:deep(.el-input--small .el-input__wrapper),
:deep(.el-select--small .el-select__wrapper),
:deep(.el-date-editor--small.el-input__wrapper) {
  height: 16px;
  line-height: 16px;
  background-color: #0a1a3a !important;
  border: 1px solid #3a5a8a !important;
  border-radius: 3px !important;
  color: #c0c4cc !important;
  box-shadow: none !important;
  font-size: 12px !important;
}
:deep(.el-input--small .el-input__inner),
:deep(.el-select--small .el-select__selected-item span),
:deep(.el-date-editor--small .el-range-input),
:deep(.el-date-editor--small .el-range-separator) {
  height: 16px !important;
  line-height: 16px !important;
  font-size: 12px !important;
  color: #c0c4cc !important;
}
:deep(.el-date-editor--small .el-range-separator) {
  padding: 0;
}
:deep(.el-input--small .el-input__icon),
:deep(.el-select--small .el-select__caret),
:deep(.el-date-editor--small .el-input__icon) {
  line-height: 28px;
  color: #c0c4cc;
}
:deep(.range-input .el-input__wrapper) {
  padding-left: 8px;
  padding-right: 8px;
}
:deep(.el-select-dropdown__item) {
  font-size: 12px;
}

/* --- Main Content Area --- */
.main-content {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden; /* Prevent scrollbars on main content */
}

/* --- Top Panel (Table + Pagination) --- */
.top-panel {
  display: flex;
  flex-direction: column;
  height: 36%; /* Initial height */
  min-height: 140px; /* Min height */
  overflow: hidden;
}
.table-container {
  flex-grow: 1;
  overflow: auto; /* Allow table itself to scroll */
  min-height: 0;
}
.pagination-container {
  flex-shrink: 0;
  background-color: #1c2d5a;
  padding: 5px 10px;
  border-top: 1px solid #3a5a8a;
  display: flex;
  justify-content: flex-end;
}

/* --- Splitter --- */
.splitter {
  height: 8px;
  background-color: #3a5a8a;
  cursor: row-resize;
  flex-shrink: 0;
  border-top: 1px solid #5a7aa4;
  border-bottom: 1px solid #5a7aa4;
}
.splitter:hover {
  background-color: #5a7aa4;
}

.middle-panel {
  flex-grow: 1;
  min-height: 120px; /* Min height */
  overflow: auto; /* Allow detail panel to scroll if content overflows */
  padding-top: 5px;
  background-color: #0a1a3a; /* Match overall background */
}

/* --- Bottom Panel (Details) --- */
.bottom-panel {
  flex-grow: 1;
  min-height: 200px; /* Min height */
  overflow: auto; /* Allow detail panel to scroll if content overflows */
  padding-top: 5px;
  background-color: #0a1a3a; /* Match overall background */
}
.bottom-panel-placeholder {
  flex-grow: 1;
  min-height: 50px; /* Smaller placeholder when details hidden */
}
.middle-detail-grid {
  display: grid;
  gap: 10px;
  height: 100%; /* Try to fill parent */
}
.detail-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
  height: 100%; /* Try to fill parent */
}
.detail-card {
  background-color: #1c2d5a;
  border-radius: 3px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}
.detail-header {
  background-color: #2979ff;
  color: #fff;
  padding: 6px 12px;
  font-weight: bold;
  font-size: 13px;
  flex-shrink: 0;
}
.detail-content {
  padding: 10px;
  flex-grow: 1;
  overflow: auto; /* Allow content within card to scroll if needed */
  min-height: 0;
}
.stats-table-wrapper {
  padding: 0;
  height: 100%;
} /* Remove padding for table */
.chart-wrapper {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 8px;
} /* Chart wrapper needs flex */
.chart-card .detail-content {
  padding: 0;
} /* Remove padding if chart wrapper handles it */

/* Chart Specific Styles */
.chart-wrapper .legend {
  margin-bottom: 5px;
  text-align: center;
  flex-shrink: 0;
  margin-top: 5px;
}
.chart-wrapper .legend-item {
  display: inline-flex;
  align-items: center;
  margin: 0 8px;
  color: #c0c4cc;
  font-size: 11px;
}
.chart-wrapper .color-box {
  width: 10px;
  height: 10px;
  margin-right: 4px;
  display: inline-block;
}
.chart-wrapper .head-max {
  background-color: #67c23a;
}
.chart-wrapper .tail-max {
  background-color: #e6a23c;
}
.chart-wrapper .chart-description {
  margin-bottom: 5px;
  color: #a0c4cc;
  text-align: center;
  flex-shrink: 0;
  font-size: 11px;
}
.chart-instance {
  width: 100%;
  flex-grow: 1;
  min-height: 150px; /* Adjusted min-height */
}

/* --- ElTable Styles (Main Table) --- */
:deep(.el-table) {
  background-color: transparent !important;
  border: none !important;
}
:deep(.el-table thead) {
  color: #b8e8ff;
}
:deep(.el-table th.el-table__cell) {
  background-color: #183272 !important;
  border-bottom: 1px solid #06279d !important;
  color: #b8e8ff;
  padding: 6px 0 !important;
}
:deep(.el-table td.el-table__cell) {
  padding: 6px 0 !important;
  border-color: #06279d !important;
  color: #c0c4cc;
  font-size: 12px;
}
:deep(.el-table tr) {
  background-color: transparent !important;
}
:deep(.el-table tr:nth-child(odd) td.el-table__cell) {
  background-color: #0f2142 !important;
}
:deep(.el-table tr:nth-child(even) td.el-table__cell) {
  background-color: #142a52 !important;
}
:deep(.el-table--enable-row-hover
    .el-table__body
    tr:hover
    > td.el-table__cell) {
  background-color: rgba(41, 121, 255, 0.2) !important;
}
:deep(.el-table__body tr.current-row > td.el-table__cell),
:deep(.el-table__body tr.selected-row > td.el-table__cell) {
  background-color: rgba(41, 121, 255, 0.3) !important;
}
/* Fixed columns specific background */
:deep(.el-table__body tr td.el-table-fixed-column--right),
:deep(.el-table__body tr:nth-child(odd) td.el-table-fixed-column--right) {
  background-color: #0f2142 !important;
}
:deep(.el-table__body tr:nth-child(even) td.el-table-fixed-column--right) {
  background-color: #142a52 !important;
}
:deep(.el-table__body tr.current-row > td.el-table-fixed-column--right),
:deep(.el-table__body tr.selected-row > td.el-table-fixed-column--right) {
  background-color: rgba(41, 121, 255, 0.3) !important;
}


/* Borders */
:deep(.el-table--border .el-table__inner-wrapper::after),
:deep(.el-table--border::after),
:deep(.el-table--border::before),
:deep(.el-table__border-left-patch),
:deep(.el-table--border .el-table__inner-wrapper::before) {
  background-color: #06279d !important;
}
:deep(.el-table td.el-table__cell),
:deep(.el-table th.el-table__cell.is-leaf) {
  border-bottom: 1px solid #06279d !important;
}
:deep(.el-table--border td.el-table__cell),
:deep(.el-table--border th.el-table__cell) {
  border-right: 1px solid #06279d !important;
}
/* Scrollbar */
:deep(.el-table__body-wrapper) {
  scrollbar-width: thin;
  scrollbar-color: #3a5a8a #142a52;
}
:deep(.el-table__body-wrapper::-webkit-scrollbar) {
  width: 6px;
  height: 6px;
}
:deep(.el-table__body-wrapper::-webkit-scrollbar-track) {
  background: #142a52;
  border-radius: 3px;
}
:deep(.el-table__body-wrapper::-webkit-scrollbar-thumb) {
  background-color: #3a5a8a;
  border-radius: 3px;
}
/* Text Highlighting */
.red-text {
  color: #ff4d4f;
  font-weight: bold;
}
:deep(.el-table__cell.red-text) {
  color: #ff4d4f;
  font-weight: bold;
}
/* Action Buttons in Table */
.action-btn {
  padding: 3px 6px;
  font-size: 11px;
  margin: 0 2px;
  border-radius: 2px;
}
.rate-btn {
  background-color: #e6a23c;
}
.rate-btn:hover {
  background-color: #ebb563;
}
.analysis-btn {
  background-color: #67c23a;
}
.analysis-btn:hover {
  background-color: #85ce61;
}

/* --- ElPagination Styles --- */
:deep(.el-pagination) {
  /* Applied within .pagination-container */
  padding: 0;
  --el-pagination-bg-color: #0a1a3a;
  --el-pagination-text-color: #c0c4cc;
  --el-pagination-button-disabled-bg-color: #183153;
  --el-pagination-button-color: #c0c4cc;
  --el-pagination-button-disabled-color: #6c757d;
  --el-pagination-hover-color: #5393ff;
  --el-color-primary: #2979ff;
}
:deep(.el-pagination button),
:deep(.el-pager li) {
  border: 1px solid #3a5a8a;
  background-color: var(--el-pagination-bg-color);
  color: var(--el-pagination-button-color);
  min-width: 24px;
  height: 24px;
  font-size: 12px;
  border-radius: 3px;
  margin: 0 2px;
}
:deep(.el-pager li.is-active) {
  background-color: var(--el-color-primary);
  border-color: var(--el-color-primary);
  color: #fff;
}
:deep(.el-pagination button:disabled) {
  background-color: var(--el-pagination-button-disabled-bg-color);
  color: var(--el-pagination-button-disabled-color);
  border-color: #3a5a8a;
  opacity: 0.7;
}
:deep(.el-pagination button:not(:disabled):hover),
:deep(.el-pager li:hover) {
  color: var(--el-pagination-hover-color);
  border-color: var(--el-pagination-hover-color);
}
:deep(.el-pagination__total) {
  color: var(--el-pagination-text-color);
  margin-right: 10px;
  font-size: 12px;
}
:deep(.el-pagination__sizes .el-select .el-input__wrapper) {
  height: 24px;
  background-color: #0a1a3a !important;
  border: 1px solid #3a5a8a !important;
  width: 90px;
}
:deep(.el-pagination__sizes .el-select .el-input__inner) {
  height: 22px !important;
  line-height: 22px !important;
  font-size: 12px !important;
  color: #c0c4cc !important;
}
:deep(.el-pagination__jump) {
  color: var(--el-pagination-text-color);
  margin-left: 10px;
  font-size: 12px;
}

:deep(.el-pagination__jump .el-input__wrapper) {
  height: 24px;
  background-color: #0a1a3a !important;
  border: 1px solid #3a5a8a !important;
  width: 35px;
  font-size: 12px !important;
}
:deep(.el-pagination__jump .el-input__inner) {
  height: 22px !important;
  line-height: 22px !important;
  font-size: 12px !important;
  color: #c0c4cc !important;
  text-align: center;
}

/* --- Statistics Table Styles --- */
:deep(.stats-table-wrapper .el-table) {
  /* More specific selector */
  --el-table-border-color: #3a5a8a;
  --el-table-header-bg-color: #0f2142;
  --el-table-header-text-color: #b8e8ff; /* Header text slightly brighter */
  --el-table-tr-bg-color: #0f2142;
  --el-table-row-hover-bg-color: #183153;
  --el-table-text-color: #c0c4cc;
  border: 1px solid #3a5a8a !important; /* Ensure outer border */
}
:deep(.stats-table-wrapper .el-table th.el-table__cell) {
  background-color: var(--el-table-header-bg-color) !important;
  color: var(--el-table-header-text-color) !important;
  border-color: #3a5a8a !important;
  padding: 5px 0 !important;
}
:deep(.stats-table-wrapper .el-table td.el-table__cell) {
  background-color: var(--el-table-tr-bg-color) !important;
  border-color: #3a5a8a !important;
  color: var(--el-table-text-color) !important;
  padding: 5px 0 !important;
}

:deep(.el-table td.el-table__cell) {
  padding: 1px 0 !important;
}

:deep(.stats-table-wrapper .el-table .el-table__cell) {
  border-right: 1px solid #3a5a8a; /* Add right border */
}
:deep(.stats-table-wrapper .el-table .el-table__cell:last-child) {
  border-right: none; /* Remove last right border */
}

:deep(.el-table .cell) {
  line-height: 14px;
}

.result-no {
  color: #ff4d4f; /* Red */
  font-weight: bold;
}





/deep/.is-leaf .cell .el-checkbox {
  display: none;
}
.el-form-item__content .el-button {
  margin: 2px !important;
  padding: 7px 11px;
}
.ColorRed {
  color: #f73773;
  font-weight: bold;
}
.echartHeader {
  height: 30px;
  margin-top: 10px;
  margin-bottom: 1px;
  text-align: center;
  background-color: #253f80;
  color: #ffffff;
  font-weight: 900;
  font-size: 17px;
}
.test-1 {
  height: 200px;
  width: 100%;
  overflow: auto;
  padding: 10px;
}
.right-box {
  /* height: calc(100vh - 435px);
  max-height: calc(100vh - 435px); */
  height: calc(100vh - 75px);
  max-height: calc(100vh - 75px);
  box-sizing: border-box;
  overflow-y: scroll;
}
.right-box::-webkit-scrollbar {
  display: block;
}
.right-box .el-checkbox {
  display: block;
}
.rm002table .el-table__body-wrapper {
  overflow: auto;
  height: 702px;
  /* height: 342px; */
}
.layout-search-header {
  width: 100%;
  height: 1px;
  background-color: #253f80;
  padding-left: 15px;
  color: #eae8c5;
  line-height: 28px;
  font-size: 0px;
  font-weight: bold;
}

.abnormal-btn { background-color: #2b0ae4; }
.abnormal:hover { background-color: #2b0ae4; }

element.style {
  position: absolute;
  left: 0px;
  top: -33px;
  width: 1300px;
  height: 249px;
  user-select: none;
  -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
  padding: 0px;
  margin: 0px;
  border-width: 0px;
}
.layout-search-header {
  width: 100%;
  height: 1px;
  background-color: #253f80;
  padding-left: 15px;
  color: #eae8c5;
  line-height: 28px;
  font-size: 0px;
  font-weight: bold;
}
.customWidth {
  width: 70%;
  margin-left: 300px;
}
.right-box {
  /* height: calc(100vh - 435px);
  max-height: calc(100vh - 435px); */
  height: calc(100vh - 75px);
  max-height: calc(100vh - 75px);
  box-sizing: border-box;
  overflow-y: scroll;
}
.right-box::-webkit-scrollbar {
  display: block;
}
.right-box .el-checkbox {
  display: block;
}
/*//头部css*/
.el-form--inline .el-form-item__label {
  text-align: center;
}
.layout-search .el-form .el-form-item {
  margin-bottom: 5px;
}
.layout-search .el-form .el-form-item .el-form-item__content .el-date-editor {
  margin-bottom: 5px;
}
.layout-search .el-form .el-form-item label {
  color: #eae8c5 !important;
  line-height: 24px;
  margin-top: 10px;
  height: 100px;
}
.layout-search .el-form .el-form-item .el-input__inner {
  background-color: #1a367a;
  width: 125px;
  height: 28px;
  color: #eae8c5;
  font-size: 14px;
}
.right-box {
  /* height: calc(100vh - 435px);
  max-height: calc(100vh - 435px); */
  height: calc(100vh - 75px);
  max-height: calc(100vh - 75px);
  box-sizing: border-box;
  overflow-y: scroll;
}
.right-box::-webkit-scrollbar {
  display: block;
}
.right-box .el-checkbox {
  display: block;
}
.el-col-4 .btn {
  margin: 40px 20px 0 0;
}
.wrap {
  //background-color: #1a367a;
}
.layout-search .el-form .el-form-item label {
  color: #eae8c5 !important;
  line-height: 57px;
  margin-top: -27px;
  height: 40px;
}
.echartHeader {
  height: 30px;
  margin-top: 10px;
  margin-bottom: 1px;
  text-align: center;
  background-color: #253f80;
  color: #ffffff;
  font-weight: 900;
  font-size: 17px;
}
.right-box {
  height: calc(100vh - 75px);
  max-height: calc(100vh - 75px);
  box-sizing: border-box;
  overflow: auto;
}
.right-box::-webkit-scrollbar {
  display: block;
}
.right-box .el-checkbox {
  display: block;
}
.el-table .cell {
  height: 25px !important;
}
span {
  color: #fff;
}



#data-view {
  width: 100%;
  height: 100%;
  color: #fff;
}
#dv-full-screen-container {
  width: 100% !important;
  height: 100% !important;
  display: flex;
  flex-direction: column;
}
.dv-border-box-10 {
  width: 100%;
  margin: 5px;
  display: inline-block;
}
.dv-border-box-11 {
  width: 100%;
  height: auto;
  padding: 4% 1% 1%;
}
.wzta {
  font-size: 18px;
  margin-top: 10px;
  font-weight: bold;
}
.weizhi {
  text-decoration: none;
  color: #23f721;
}
#app1_1,
#app1 {
  width: 100%;
  height: 300px;
  padding-top: 20px;
}

  /* 异常明细弹窗样式（与 LayOutJudge.vue 保持一致） */
  :deep(.abnormal-dialog) {
    background: #1a2a4a !important;
    border-radius: 12px;
    box-shadow: 0 8px 32px 0 rgba(0,40,120,0.35);
    border: 1px solid #3a5a8a;
    animation: dialogFadeIn 0.3s ease-out;
  }

  @keyframes dialogFadeIn {
    from {
      opacity: 0;
      transform: scale(0.9) translateY(-20px);
    }
    to {
      opacity: 1;
      transform: scale(1) translateY(0);
    }
  }

  :deep(.abnormal-dialog .el-dialog__header) {
    background: linear-gradient(135deg, #2a5caa 0%, #1e3a6f 100%);
    border-radius: 12px 12px 0 0;
    padding: 15px 20px;
    border-bottom: 2px solid #3a5a8a;
  }

  :deep(.abnormal-dialog .el-dialog__title) {
    color: #fff !important;
    font-size: 16px;
    font-weight: bold;
  }

  :deep(.abnormal-dialog .el-dialog__headerbtn .el-dialog__close) {
    color: #fff !important;
    font-size: 18px;
  }

  :deep(.abnormal-dialog .el-dialog__body) {
    padding: 0;
    background: #0a1a3a;
    border-radius: 0 0 12px 12px;
  }

  /* 异常明细弹窗内容样式 */
  .abnormal-dialog-content {
    background: #0a1a3a;
    color: #c0c4cc;
    font-family: 'Microsoft YaHei', 'Segoe UI', sans-serif;
    font-size: 13px;
    height: 100%;
    display: flex;
    flex-direction: column;
  }

  /* 表格面板样式 */
  .abnormal-table-panel {
    background: #1c2d5a;
    margin: 15px 0px;
    border-radius: 8px;
    overflow: hidden;
    flex-grow: 1;
    min-height: 0;
    border: 1px solid #3a5a8a;
  }

  /* 异常明细表格样式 */
  :deep(.abnormal-table-panel .el-table) {
    background-color: transparent;
    --el-table-border-color: #3a5a8a;
    --el-table-header-bg-color: #2a5caa;
    --el-table-header-text-color: #fff;
    --el-table-tr-bg-color: #0f2142;
    --el-table-row-hover-bg-color: #183153;
    --el-table-text-color: #c0c4cc;
    --el-table-border: none;
  }

  :deep(.abnormal-table-panel .el-table__header-wrapper th.el-table__cell) {
    background: linear-gradient(135deg, #2a5caa 0%, #1e3a6f 100%) !important;
    color: #fff !important;
    font-weight: bold;
    border: none;
    position: relative;
  }

  :deep(.abnormal-table-panel .el-table__header-wrapper th.el-table__cell::after) {
    content: '';
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    height: 2px;
    background: linear-gradient(90deg, transparent 0%, #2979ff 50%, transparent 100%);
  }

  :deep(.abnormal-table-panel .el-table__body td.el-table__cell) {
    background-color: #0f2142;
    border: none;
    transition: all 0.3s ease;
  }

  :deep(.abnormal-table-panel .el-table__body tr:hover td.el-table__cell) {
    background-color: #183153 !important;
    transform: scale(1.01);
  }

  :deep(.abnormal-table-panel .el-table__body tr.current-row td.el-table__cell) {
    background-color: #263451 !important;
    color: #fff !important;
  }

  /* 条纹行样式 */
  :deep(.abnormal-table-panel .el-table__body tr.abnormal-stripe-row td.el-table__cell) {
    background-color: #142a52;
  }

  :deep(.abnormal-table-panel .el-table__body tr.abnormal-stripe-row:hover td.el-table__cell) {
    background-color: #1a3a62 !important;
  }

  /* 缺陷代码高亮样式 */
  .defect-code-high, .defect-class-high {
    color: #ff4d4f !important;
    font-weight: bold;
    background: rgba(255, 77, 79, 0.1);
    padding: 2px 6px;
    border-radius: 4px;
    border: 1px solid rgba(255, 77, 79, 0.3);
  }

  .defect-code-normal, .defect-class-normal {
    color: #67c23a;
    font-weight: 500;
  }

  /* 异常红色文本（单元格类） */
  :deep(.abnormal-table-panel .el-table__cell.abnormal-red-text) {
    color: #ff4d4f !important;
    font-weight: bold;
  }

  /* 分页面板样式 */
  .abnormal-pagination-panel {
    background: linear-gradient(135deg, #1c2d5a 0%, #142a52 100%);
    padding: 15px 20px;
    border-top: 2px solid #3a5a8a;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    flex-shrink: 0;
  }

  /* 异常明细分页样式 */
  :deep(.abnormal-pagination-panel .el-pagination) {
    --el-pagination-bg-color: #0a1a3a;
    --el-pagination-text-color: #c0c4cc;
    --el-pagination-button-disabled-bg-color: #183153;
    --el-pagination-button-color: #c0c4cc;
    --el-pagination-button-disabled-color: #6c757d;
    --el-pagination-hover-color: #2979ff;
    --el-color-primary: #2979ff;
  }

  :deep(.abnormal-pagination-panel .el-pagination__total) {
    color: #c0c4cc;
    margin-right: 15px;
    font-weight: 500;
  }

  :deep(.abnormal-pagination-panel .el-pagination button),
  :deep(.abnormal-pagination-panel .el-pager li) {
    min-width: 32px;
    height: 32px;
    padding: 0 8px;
    margin: 0 3px;
    background: linear-gradient(135deg, #0a1a3a 0%, #142a52 100%);
    border: 1px solid #3a5a8a;
    border-radius: 6px;
    color: #c0c4cc;
    font-size: 13px;
    transition: all 0.3s ease;
  }

  :deep(.abnormal-pagination-panel .el-pager li.is-active) {
    background: linear-gradient(135deg, #2979ff 0%, #1e5fcc 100%);
    border-color: #2979ff;
    color: #fff;
    transform: scale(1.05);
  }

  :deep(.abnormal-pagination-panel .el-pagination button:not(:disabled):hover),
  :deep(.abnormal-pagination-panel .el-pager li:hover) {
    color: #2979ff;
    border-color: #2979ff;
    transform: translateY(-1px);
    box-shadow: 0 2px 8px rgba(41, 121, 255, 0.2);
  }

  :deep(.abnormal-pagination-panel .el-pagination button:disabled) {
    background: #183153;
    color: #6c757d;
    border-color: #3a5a8a;
    opacity: 0.6;
  }

  /* 滚动条样式 */
  :deep(.abnormal-table-panel .el-table__body-wrapper) {
    scrollbar-width: thin;
    scrollbar-color: #3a5a8a #142a52;
  }

  :deep(.abnormal-table-panel .el-table__body-wrapper::-webkit-scrollbar) {
    width: 8px;
    height: 8px;
  }

  :deep(.abnormal-table-panel .el-table__body-wrapper::-webkit-scrollbar-track) {
    background: #142a52;
    border-radius: 4px;
  }

  :deep(.abnormal-table-panel .el-table__body-wrapper::-webkit-scrollbar-thumb) {
    background: linear-gradient(135deg, #3a5a8a 0%, #2979ff 100%);
    border-radius: 4px;
    border: 2px solid #142a52;
  }

  :deep(.abnormal-table-panel .el-table__body-wrapper::-webkit-scrollbar-thumb:hover) {
    background: linear-gradient(135deg, #5a7aa4 0%, #5393ff 100%);
  }

  /* 表格行进入动画 */
  :deep(.abnormal-table-panel .el-table__body tr) {
    animation: rowSlideIn 0.3s ease-out;
  }

  @keyframes rowSlideIn {
    from {
      opacity: 0;
      transform: translateX(-20px);
    }
    to {
      opacity: 1;
      transform: translateX(0);
    }
  }

  /* 超差原因面板 */
  .abnormal-cause-panel {
    background: #1c2d5a;
    border: 1px solid #3a5a8a;
    border-radius: 8px;
    padding: 12px 14px;
    margin: 8px 0 0 0;
  }

  .abnormal-cause-panel .cause-item {
    display: flex;
    align-items: flex-start;
    margin: 4px 0;
  }

  .abnormal-cause-panel .cause-label {
    color: #b8e8ff;
    font-weight: 600;
    min-width: 110px;
    text-align: right;
    margin-right: 8px;
  }

  .abnormal-cause-panel .cause-text {
    color: #c0c4cc;
    white-space: pre-wrap;
    word-break: break-all;
    flex: 1;
  }

  /* 超差因子样式 */
  .abnormal-cause-panel .cause-section-title {
    color: #2979ff;
    font-weight: bold;
    font-size: 14px;
    margin-bottom: 8px;
    text-align: center;
    border-bottom: 1px solid #3a5a8a;
    padding-bottom: 6px;
  }

  .abnormal-cause-panel .factor-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 8px;
  }

  .abnormal-cause-panel .factor-item {
    display: flex;
    align-items: center;
    padding: 6px 8px;
    background: rgba(41, 121, 255, 0.1);
    border: 1px solid rgba(41, 121, 255, 0.3);
    border-radius: 4px;
  }

  .abnormal-cause-panel .factor-label {
    color: #b8e8ff;
    font-weight: 500;
    font-size: 12px;
    margin-right: 6px;
    white-space: nowrap;
  }

  .abnormal-cause-panel .factor-value {
    color: #67c23a;
    font-weight: bold;
    font-size: 12px;
    flex: 1;
    text-align: right;
  }
</style>
